package com.smm.util;


import com.smm.common.CustomException;
import com.smm.common.ResultCode;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * jwt工具,使用对称加密算法
 */


@Component
@ConfigurationProperties(prefix = "jwt.config")
public class JwtTokenUtil {
    private static Logger log = LoggerFactory.getLogger(JwtTokenUtil.class);


    public static final String AUTH_HEADER_KEY = "Authorization";

    public static final String TOKEN_PREFIX = "Bearer ";


    private static String clientId;
    private static String base64Secret;
    private static String name;
    private static int expiresSecond;

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        JwtTokenUtil.clientId = clientId;
    }

    public String getBase64Secret() {
        return base64Secret;
    }

    public void setBase64Secret(String base64Secret) {
        JwtTokenUtil.base64Secret = base64Secret;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        JwtTokenUtil.name = name;
    }

    public int getExpiresSecond() {
        return expiresSecond;
    }

    public void setExpiresSecond(int expiresSecond) {
        JwtTokenUtil.expiresSecond = expiresSecond;
    }

    /**
     * @param jsonWebToken 接收到的token
     * @return
     */
    public static Claims parseJWT(String jsonWebToken) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(base64Secret))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (ExpiredJwtException eje) {
            log.error("===== Token过期 =====", eje);
            throw new CustomException(ResultCode.PERMISSION_TOKEN_EXPIRED);
        } catch (Exception e) {
            log.error("===== token解析异常 =====", e);
            throw new CustomException(ResultCode.PERMISSION_TOKEN_INVALID);
        }
    }

    /**
     * @param userId
     * @param username
     * @param role
     * @return
     */
    public static String createJWT(Integer userId, String username, String role) {
        try {
            //使用的加密算法,对称加密,加密解密一套密钥
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

            long nowMillis = System.currentTimeMillis();
            Date now = new Date(nowMillis);

            //生成签名密钥
            byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
            Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
            //userId加密
            String encryId = Base64Util.encode(username);

            //添加构成JWT参数
            JwtBuilder builder = Jwts.builder().setHeaderParam("type", "JWT")
                    .claim("role", role)
                    .claim("userId", userId)
                    .setSubject(username)//签名主体,即代表签名拥有者
                    .setIssuer(clientId)//代表签名的签发客户端
                    .setIssuedAt(new Date())//签发日期
                    .setAudience(name)//代表这个JWT的接收对象
                    .signWith(signatureAlgorithm, signingKey);
            int TTLMillis = expiresSecond;
            if (TTLMillis >= 0) {
                long expMillis = nowMillis + TTLMillis;
                Date exp = new Date(expMillis);
                builder.setExpiration(exp)//JWT过期时间
                        .setNotBefore(now);//JWT生效时间
            }
            return builder.compact();

        } catch (Exception e) {
            log.error("签名失败", e);
            throw new CustomException(ResultCode.PERMISSION_SIGNATURE_ERROR);
        }
    }
}
